package com.atlige.gzmall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atlige.common.utils.HttpUtils;
import com.atlige.gzmall.member.dao.MemberLevelDao;
import com.atlige.gzmall.member.entity.MemberLevelEntity;
import com.atlige.gzmall.member.exception.PhoneExistException;
import com.atlige.gzmall.member.exception.UsernameExistException;
import com.atlige.gzmall.member.service.MemberLevelService;
import com.atlige.gzmall.member.vo.MemberLoginVo;
import com.atlige.gzmall.member.vo.MemberRegistVo;
import com.atlige.gzmall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atlige.common.utils.PageUtils;
import com.atlige.common.utils.Query;

import com.atlige.gzmall.member.dao.MemberDao;
import com.atlige.gzmall.member.entity.MemberEntity;
import com.atlige.gzmall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo memberRegistVo) {
        MemberEntity memberEntity = new MemberEntity();
        // 设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());
        // 设置手机号
        // 检查用户名和手机号是否唯一，为了让controller感知异常，异常机制
        checkPhoneUnique(memberRegistVo.getPhone());
        checkUsernameUnique(memberRegistVo.getUserName());

        memberEntity.setMobile(memberRegistVo.getPhone());
        memberEntity.setUsername(memberRegistVo.getUserName());
        memberEntity.setNickname(memberRegistVo.getUserName());
        // 密码要加密处理
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        memberEntity.setPassword(passwordEncoder.encode(memberRegistVo.getPassword()));

        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        Integer selectCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (selectCount > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException{
        Integer selectCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (selectCount > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo loginVo) {
        String loginacct = loginVo.getLoginacct();
        String password = loginVo.getPassword();
        // 1、去数据库查询用户
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).
                or().eq("mobile", loginacct));
        if (memberEntity == null) {
            // 登录失败
            return null;
        }else {
            // 数据库的password
            String DbPassword = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            // 密码匹配
            boolean matches = passwordEncoder.matches(password, DbPassword);
            if (matches){
                return memberEntity;
            }else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        String uid = socialUser.getUid();
        // 登录和注册合并
        MemberEntity socialEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (socialEntity != null){
            // 用户已经注册
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setId(socialEntity.getId());
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            baseMapper.updateById(memberEntity);
            socialEntity.setAccessToken(socialUser.getAccess_token());
            socialEntity.setExpiresIn(socialUser.getExpires_in());
            return socialEntity;
        }else {
            //2、没有注册
            MemberEntity regist = new MemberEntity();
            try {
                // 查询当前社交用户信息 https://api.weibo.com/2/users/show.json
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get",
                        new HashMap<String, String>(),
                        query);
                if (response.getStatusLine().getStatusCode() == 200){
                    String toString = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(toString);
                    // 昵称
                    String name = jsonObject.getString("name");
                    // 性别
                    String gender = jsonObject.getString("gender");
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {}
            regist.setSocialUid(socialUser.getUid());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());
            baseMapper.insert(regist);
            return regist;
        }
    }

}
